package com.wuax.filter;

import com.wuax.util.CommonUtil;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截器
 */
public class UserFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest hrequest = (HttpServletRequest) request;
        HttpServletResponse hresponse = (HttpServletResponse) response;

        // 不拦截的路径（登录，网站图标，静态资源，登录验证）
        String servletPath = hrequest.getServletPath();
        if (servletPath != null && !"".equals(servletPath)
                && ("/login".equals(servletPath)
                || "/favicon.ico".equals(servletPath)
                || servletPath.startsWith("/static")
                || "/loginCheck".equals(servletPath))) {
            chain.doFilter(hrequest, hresponse);
            return;
        }

        HttpSession session = hrequest.getSession(false);
        //通过session判断用户是否登录
        if (session != null && session.getAttribute("sys_user") != null) {
            chain.doFilter(hrequest, hresponse);
        } else {
            // 如果未登录，切请求是异步，则返回401，否则重定向到登录页面
            if (hrequest.getHeader("x-requested-with") != null && hrequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                hresponse.setStatus(401);
            } else {
                hresponse.sendRedirect(CommonUtil.getBasePath(hrequest).concat("login"));
            }
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    public void destroy() {
        // TODO Auto-generated method stub

    }

}
